import os
import time
import random
import numpy as np
import cv2 as cv
import pygame, sys, os
from pygame.locals import *

drivers = ['/dev/fb1','/dev/fb0']

camera = cv.VideoCapture(0)
camera.set(cv.CAP_PROP_FRAME_WIDTH, 320)
camera.set(cv.CAP_PROP_FRAME_HEIGHT, 240)

classifier = cv.CascadeClassifier("haarcascade_frontalface_alt.xml")


# Uncomment if you have a touch panel and find the X value for your device
# os.environ["SDL_MOUSEDRV"] = "TSLIB"
# os.environ["SDL_MOUSEDEV"] = "/dev/input/eventX"

class pyscope:
    screen = None;

    def __init__(self):
        "Ininitializes a new pygame screen using the framebuffer"
        # Based on "Python GUI in Linux frame buffer"
        # http://www.karoltomala.com/blog/?p=679
        disp_no = os.getenv("DISPLAY")
        if disp_no:
            print("I'm running under X display = " + str(disp_no))

        # Check which frame buffer drivers are available
        # Start with fbcon since directfb hangs with composite output

        found = False
        # 寻找显示器设备
        for driver in drivers:
            # Make sure that SDL_VIDEODRIVER is set
            if not os.getenv('SDL_FBDEV'):
                os.putenv('SDL_FBDEV', driver)
            try:
                # 初始化显示模块,显示模块在初始化之前无法执行任何操作。
                pygame.display.init()
            except pygame.error:
                # 检测显示器设备是否错误
                print("Driver: " + str(driver) + " failed.")
                continue
            found = True
            break

        if not found:
            raise Exception('No suitable video driver found!')

        # 创建一个视频显示信息对象
        size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
        print("Framebuffer size: %d x %d" % (size[0], size[1]))
        # 初始化显示窗口或屏幕
        self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
        # Clear the screen to start
        self.screen.fill((255, 0, 0))
        # Initialise font support
        pygame.font.init()
        # Render the screen
        pygame.display.update()

    def __del__(self):
        "Destructor to make sure pygame shuts down, etc."

    def test(self):
        # Fill the screen with red (255, 0, 0)
        # 屏幕颜色全黑
        red = (0, 0, 0)
        self.screen.fill(red)

        box = pygame.draw.rect(self.screen, (0, 0, 255), (140, 0, 20, 10))

        while True:
            # 触摸
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    print("Pos: %sx%s\n" % pygame.mouse.get_pos())
                    if box.collidepoint(pygame.mouse.get_pos()):
                        pygame.quit()
                        sys.exit()
                        # Update the display

            # 读取摄像头画面
            ret, frame = camera.read()
            print("frame: " + str(frame.shape))

            # 通过插值的方式来改变图像的尺寸
            frame = cv.resize(frame, (240, 135))

            # 调用训练好的分类器和自带的检测函数
            faceRects = classifier.detectMultiScale(cv.cvtColor(frame, cv.COLOR_BGR2GRAY), \
                                                    scaleFactor=1.2, minNeighbors=3, minSize=(20, 20))
            if len(faceRects):
                for faceRect in faceRects:
                    x, y, w, h = faceRect
                    cv.rectangle(frame, (x, y), (x + h, y + w), (0, 0, 255), 2)

            frame = cv.cvtColor(frame, cv.COLOR_BGR2RGB)
            frame = np.rot90(frame)
            frame = pygame.surfarray.make_surface(frame)
            self.screen.blit(frame, (0, 0))

            pygame.display.update()


# Create an instance of the PyScope class
scope = pyscope()
scope.test()
